/***
  *****************************************************************************
  * @file		key.c
  * @author			
  * @version	V1.0
  * @date 		2014-11-15
  * @brief 
  *****************************************************************************
 ***/
#include <stdio.h>
#include "aero_key.h"
#include <wiringPi.h>

extern    unsigned char key_up;//按键按松开标志

/** 
  * @name	void KEY_Init(void)
  * @brief  KEY初始化
  * @param	none
  * @retval	none
  */ 
void aeroKeyInit(void)
{
    printf( "aero_key\n" );
//    wiringPiSetup();
    pullUpDnControl(KEY1,PUD_DOWN);
	pinMode(KEY1,INPUT);
	pinMode(KEY2,INPUT);
	pinMode(KEY3,INPUT);	
	pinMode(KEY4,INPUT);
}

/** 
  * @name	u8 KEY_Scan(u8 mode)
  * @brief  按键处理函数, 这是正点原子的程序
  * @param	mode:0,不支持连续按;1,支持连续按;
  * @retval	0，没有任何按键按下
  *			1，KEY0按下
  *			2，KEY1按下
  *			3，KEY2按下 
  *			4，WKUP按下 WK_UP
  *			注意此函数有响应优先级,KEY0>KEY1>KEY2>WK_UP!!
  */ 
unsigned char aeroKeyScan(unsigned char mode)
{
//    unsigned char key_up=1;//按键按松开标志
//    if(mode)key_up=1;  //支持连按
    
    if (key_up&&(digitalRead(KEY1)||digitalRead(KEY2)||digitalRead(KEY3)||digitalRead(KEY4)))
    {
        delay(1);
        key_up = 0;
        if (digitalRead(KEY1)) return KEY_UP;//KEY_RIGHT;
        else if (digitalRead(KEY2)) return KEY_DOWN;//KEY_LEFT;
        else if (digitalRead(KEY3)) return KEY_RIGHT;//KEY_UP;
        else if (digitalRead(KEY4)) return KEY_LEFT;//KEY_DOWN;
    }else if ((!digitalRead(KEY1))&&(!digitalRead(KEY2))&&(!digitalRead(KEY3))&&(!digitalRead(KEY4)))
        key_up = 1;
    return 0;
	// if(key_up&&(KEY0==0||KEY1==0||KEY2==0||WK_UP==1))
	// {
	// 	delay_ms(10);//去抖动 
	// 	key_up=0;
	// 	if(KEY0==0)return KEY_RIGHT;
	// 	else if(KEY1==0)return KEY_DOWN;
	// 	else if(KEY2==0)return KEY_LEFT;
	// 	else if(WK_UP==1)return KEY_UP;
	// }else if(KEY0==1&&KEY1==1&&KEY2==1&&WK_UP==0)key_up=1; 	    
 	// return 0;// 无按键按下
}

void keymain(void)
{
    wiringPiSetup();
    aeroKeyInit();
    unsigned char tmp;
    while(1)
    {
        tmp = aeroKeyScan(1);
        printf("%d \n",tmp);
    }
}